import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)

let router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})
router.beforeEach(async (to, from, next) => {

  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  //用户登录
  if (token) {
    if (to.path == '/login' || to.path == '/register') {
      next('/')
    } else {
      if (name) {
        next()
      } else {
        try {
          await store.dispatch("getUserInfo");
          next()
        } catch (error) {
          await store.dispatch("getUserLogOut");
          next('/')
        }
      }
    }
  }
  //未登录
  else {
    next()
  }
})
export default router
